<template>
  <div class="device-info-container">
    <!-- 左侧导航栏 -->
    <div class="device-nav">
      <el-tree
          :data="deviceData"
          default-expand-all
          :expand-on-click-node="false"
          class="device-tree"
          @node-click="handleNodeClick"
      >
        <template #default="{ data }">
          <div class="custom-tree-node">
            <span>{{ data.label }}</span>
            <span v-if="data.children && data.children.length > 0" class="tree-arrow">></span>
          </div>
        </template>
      </el-tree>
    </div>

    <!-- 右侧内容区域 -->
    <div class="device-content">
      <!-- 搜索栏区域 -->
      <div class="search-box">
        <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" @keyup.enter="onSubmit">

          <el-form-item label="设备名称" prop="deviceName">
            <el-select v-model="searchInfo.deviceName" clearable filterable placeholder="请选择" @clear="()=>{searchInfo.deviceName=undefined}">
              <el-option v-for="(item,key) in deviceNameOptions" :key="key" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="设备型号" prop="deviceName">
            <el-select v-model="searchInfo.equipmentModel" clearable filterable placeholder="请选择" @clear="()=>{searchInfo.equipmentModel=undefined}">
              <el-option v-for="(item,key) in equipmentModelOptions" :key="key" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="资料类型" prop="dataType">
            <el-select v-model="searchInfo.dataType" clearable filterable placeholder="请选择" @clear="()=>{searchInfo.dataType=undefined}">
              <el-option v-for="(item,key) in dataTypeOptions" :key="key" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="资料格式" prop="dataFormat">
            <el-select v-model="searchInfo.dataFormat" clearable filterable placeholder="请选择" @clear="()=>{searchInfo.dataFormat=undefined}">
              <el-option v-for="(item,key) in dataFormatOptions" :key="key" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
            <el-button icon="refresh" @click="onReset">重置</el-button>
            <el-button link type="primary" icon="arrow-down" @click="showAllQuery=true" v-if="!showAllQuery">展开</el-button>
            <el-button link type="primary" icon="arrow-up" @click="showAllQuery=false" v-else>收起</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <div class="table-box">
        <!-- 操作按钮区域 -->
        <div class="gva-btn-list">
          <el-button type="primary" icon="plus" @click="openDialog()">新增</el-button>
          <el-button icon="delete" style="margin-left: 10px;" :disabled="!multipleSelection.length" @click="onDelete">删除</el-button>
          <ExportTemplate template-id="device_Information" />
          <ExportExcel template-id="device_Information" filterDeleted/>
          <ImportExcel template-id="device_Information" @on-success="getTableData" />
        </div>
        <el-table
            ref="multipleTable"
            style="width: 100%"
            tooltip-effect="dark"
            :data="tableData"
            row-key="ID"
            @selection-change="handleSelectionChange"
        >

          <el-table-column type="selection" width="55" />

          <el-table-column align="left" label="设备型号" prop="equipmentModel" width="120" />

          <el-table-column align="left" label="资料标题" prop="dataTitle" width="120" />

          <el-table-column align="left" label="文件大小" prop="fileSize" width="120" />

          <el-table-column align="left" label="更新日期" prop="updateDate" width="180">
            <template #default="scope">{{ formatDate(scope.row.updateDate) }}</template>
          </el-table-column>

          <el-table-column align="left" label="操作" fixed="right" :min-width="appStore.operateMinWith">
            <template #default="scope">
              <el-button type="primary" link class="table-button" @click="getDetails(scope.row)"><el-icon style="margin-right: 5px"><InfoFilled /></el-icon>查看</el-button>
              <el-button type="primary" link icon="edit" class="table-button" @click="updateInformationFunc(scope.row)">编辑</el-button>
              <el-button  type="primary" link icon="delete" @click="deleteRow(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <div class="gva-pagination">
          <el-pagination
              layout="total, sizes, prev, pager, next, jumper"
              :current-page="page"
              :page-size="pageSize"
              :page-sizes="[10, 30, 50, 100]"
              :total="total"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
          />
        </div>
      </div>
      <el-drawer destroy-on-close :size="appStore.drawerSize" v-model="dialogFormVisible" :show-close="false" :before-close="closeDialog">
        <template #header>
          <div class="flex justify-between items-center">
            <span class="text-lg">{{type==='create'?'新增':'编辑'}}</span>
            <div>
              <el-button :loading="btnLoading" type="primary" @click="enterDialog">确 定</el-button>
              <el-button @click="closeDialog">取 消</el-button>
            </div>
          </div>
        </template>

        <el-form :model="formData" label-position="top" ref="elFormRef" :rules="rule" label-width="80px">
          <el-form-item label="设备型号:" prop="equipmentModel">
            <el-input v-model="formData.equipmentModel" :clearable="true" placeholder="请输入设备型号" />
          </el-form-item>
          <el-form-item label="设备名称:" prop="deviceName">
            <el-input v-model="formData.deviceName" :clearable="true" placeholder="请输入设备名称" />
          </el-form-item>
          <el-form-item label="资料类型:" prop="dataType">
            <el-select v-model="formData.dataType" placeholder="请选择资料类型" style="width:100%" filterable :clearable="true">
              <el-option v-for="(item,key) in dataTypeOptions" :key="key" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="资料格式:" prop="dataFormat">
            <el-select v-model="formData.dataFormat" placeholder="请选择资料格式" style="width:100%" filterable :clearable="true">
              <el-option v-for="(item,key) in dataFormatOptions" :key="key" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="资料标题:" prop="dataTitle">
            <el-input v-model="formData.dataTitle" :clearable="true" placeholder="请输入资料标题" />
          </el-form-item>
          <el-form-item label="文件大小:" prop="fileSize">
            <el-input-number v-model="formData.fileSize" style="width:100%" :precision="2" :clearable="true" />
          </el-form-item>
          <el-form-item label="更新日期:" prop="updateDate">
            <el-date-picker v-model="formData.updateDate" type="date" style="width:100%" placeholder="选择日期" :clearable="true" />
          </el-form-item>
        </el-form>
      </el-drawer>

      <el-drawer destroy-on-close :size="appStore.drawerSize" v-model="detailShow" :show-close="true" :before-close="closeDetailShow" title="查看">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="设备型号">
            {{ detailFrom.equipmentModel }}
          </el-descriptions-item>
          <el-descriptions-item label="设备名称">
            {{ detailFrom.deviceName }}
          </el-descriptions-item>
          <el-descriptions-item label="资料类型">
            {{ detailFrom.dataType }}
          </el-descriptions-item>
          <el-descriptions-item label="资料格式">
            {{ detailFrom.dataFormat }}
          </el-descriptions-item>
          <el-descriptions-item label="资料标题">
            {{ detailFrom.dataTitle }}
          </el-descriptions-item>
          <el-descriptions-item label="文件大小">
            {{ detailFrom.fileSize }}
          </el-descriptions-item>
          <el-descriptions-item label="更新日期">
            {{ detailFrom.updateDate }}
          </el-descriptions-item>
        </el-descriptions>
      </el-drawer>
    </div>
  </div>
</template>

<script setup>
import {
  createInformation,
  deleteInformation,
  deleteInformationByIds,
  updateInformation,
  findInformation,
  getInformationList
} from '@/api/device/information'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict, filterDataSource, returnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'
// 引入按钮权限标识
import { useBtnAuth } from '@/utils/btnAuth'
import { useAppStore } from "@/pinia"

// 导出组件
import ExportExcel from '@/components/exportExcel/exportExcel.vue'
// 导入组件
import ImportExcel from '@/components/exportExcel/importExcel.vue'
// 导出模板组件
import ExportTemplate from '@/components/exportExcel/exportTemplate.vue'

defineOptions({
  name: 'Information'
})
// 按钮权限实例化
const btnAuth = useBtnAuth()

// 提交按钮loading
const btnLoading = ref(false)
const appStore = useAppStore()

// 控制更多查询条件显示/隐藏状态
const showAllQuery = ref(false)

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
  equipmentModel: '',
  deviceName: '',
  dataType: '',
  dataFormat: '',
  dataTitle: '',
  fileSize: 0,
  updateDate: new Date(),
})

// 验证规则
const rule = reactive({
  dataType: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
    {
      whitespace: true,
      message: '不能只输入空格',
      trigger: ['input', 'blur'],
    }],
  dataFormat: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
    {
      whitespace: true,
      message: '不能只输入空格',
      trigger: ['input', 'blur'],
    }]
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const deviceData = ref([
  {
    label: '光刻机',
    children: [
      { label: 'SZ-GK01' },
      { label: 'SZ-GK02' }
    ]
  },
  {
    label: '刻蚀机',
    children: [
      { label: 'SZ-KS01' },
      { label: 'SZ-KS02' },
      { label: 'SZ-KS03' }
    ]
  },
  {
    label: '离子注入机',
    children: [
      { label: 'SZ-ZR01' },
      { label: 'SZ-ZR02' }
    ]
  },
  {
    label: '晶圆划片机',
    children: [
      { label: 'SZ-JY01' },
      { label: 'SZ-JY02' }
    ]
  }
])
const deviceNameOptions = ref([
  { label: '全部', value: '' },
  { label: '光刻机', value: '光刻机' },
  { label: '刻蚀机', value: '刻蚀机' },
  { label: '离子注入机', value: '离子注入机' },
  { label: '晶圆划片机', value: '晶圆划片机' }
])

const equipmentModelOptions = ref([
  { label: '全部', value: '' },
  { label: 'SZ-GK01', value: 'SZ-GK01' },
  { label: 'SZ-GK02', value: 'SZ-GK02' },
  { label: 'SZ-KS01', value: 'SZ-KS01' },
  { label: 'SZ-KS02', value: 'SZ-KS02' },
  { label: 'SZ-KS03', value: 'SZ-KS03' },
  { label: 'SZ-ZR01', value: 'SZ-ZR01' },
  { label: 'SZ-ZR02', value: 'SZ-ZR02' },
  { label: 'SZ-JY01', value: 'SZ-JY01' },
  { label: 'SZ-JY02', value: 'SZ-JY02' }
])
const dataTypeOptions = ref([
  { label: '全部', value: '' },
  { label: '设备彩页', value: '设备彩页' },
  { label: '设备画册', value: '设备画册' },
  { label: '用户手册', value: '用户手册' },
  { label: '安装手册', value: '安装手册' },
  { label: '配置文件', value: '配置文件' },
  { label: '演示视频', value: '演示视频' },
  { label: '常见问题', value: '常见问题' }
])
const dataFormatOptions = ref([
  { label: '全部', value: '' },
  { label: 'pdf', value: 'pdf' },
  { label: 'zip/rar', value: 'zip/rar' },
  { label: 'apk', value: 'apk' },
  { label: 'html', value: 'html' },
  { label: 'dxf', value: 'dxf' },
  { label: 'stp', value: 'stp' },
  { label: 'mp4', value: 'mp4' }
])
const searchInfo = ref({})
const tableData = ref({})

// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

// 查询
const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    getTableData()
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 查询
const getTableData = async() => {
  const table = await getInformationList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async() => {
  dataTypeOptions.value = await getDictFunc('dataType')
  dataFormatOptions.value = await getDictFunc('dataFormat')
}

// 获取需要的字典 可能为空 按需保留
setOptions()

// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteInformationFunc(row)
  })
}

// 多选删除
const onDelete = async() => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async() => {
    const IDs = []
    if (multipleSelection.value.length === 0) {
      ElMessage({
        type: 'warning',
        message: '请选择要删除的数据'
      })
      return
    }
    multipleSelection.value &&
    multipleSelection.value.map(item => {
      IDs.push(item.ID)
    })
    const res = await deleteInformationByIds({ IDs })
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
      if (tableData.value.length === IDs.length && page.value > 1) {
        page.value--
      }
      getTableData()
    }
  })
}

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateInformationFunc = async(row) => {
  const res = await findInformation({ ID: row.ID })
  type.value = 'update'
  if (res.code === 0) {
    formData.value = res.data
    dialogFormVisible.value = true
  }
}

// 删除行
const deleteInformationFunc = async(row) => {
  const res = await deleteInformation({ ID: row.ID })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    getTableData()
  }
}

// 处理树节点点击
const handleNodeClick = (data, node) => {
  // 这里应该根据点击的节点筛选表格数据
  console.log('节点点击:', data, node)
  if (node.level === 1) { // 如果是父节点
    searchInfo.value.deviceName = data.label
    searchInfo.value.equipmentModel = undefined
  } else if (node.level === 2) { // 如果是子节点
    searchInfo.value.equipmentModel = data.label
    searchInfo.value.deviceName = node.parent.label
  }
  page.value = 1
  getTableData()
}

// 弹窗控制标记
const dialogFormVisible = ref(false)

// 打开弹窗
const openDialog = () => {
  type.value = 'create'
  dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    equipmentModel: '',
    deviceName: '',
    dataType: '',
    dataFormat: '',
    dataTitle: '',
    fileSize: 0,
    updateDate: new Date(),
  }
}
// 弹窗确定
const enterDialog = async() => {
  btnLoading.value = true
  elFormRef.value?.validate(async(valid) => {
    if (!valid) return btnLoading.value = false
    let res
    switch (type.value) {
      case 'create':
        res = await createInformation(formData.value)
        break
      case 'update':
        res = await updateInformation(formData.value)
        break
      default:
        res = await createInformation(formData.value)
        break
    }
    btnLoading.value = false
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      closeDialog()
      getTableData()
    }
  })
}

const detailFrom = ref({})

// 查看详情控制标记
const detailShow = ref(false)

// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true
}

// 打开详情
const getDetails = async(row) => {
  // 打开弹窗
  const res = await findInformation({ ID: row.ID })
  if (res.code === 0) {
    detailFrom.value = res.data
    openDetailShow()
  }
}

// 关闭详情弹窗
const closeDetailShow = () => {
  detailShow.value = false
  detailFrom.value = {}
}
</script>

<style scoped>
.device-info-container {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

.device-nav {
  width: 220px;
  border-right: 1px solid #ebeef5;
  height: 100%;
  overflow-y: auto;
}

.device-content {
  flex: 1;
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.search-box {
  margin-bottom: 20px;
}

.search-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.table-box {
  height: calc(100% - 80px);
  display: flex;
  flex-direction: column;
}

.gva-btn-list {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.table-card {
  flex: 1;
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.el-table {
  width: 100%;
  border: none;
}

.gva-pagination {
  margin-top: 15px;
  padding: 15px;
  display: flex;
  justify-content: flex-end;
  background-color: white;
}

.el-form-item {
  margin-bottom: 0;
}

.el-select {
  width: 100%;
}

.el-button {
  margin-right: 10px;
}

.el-table {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f5f7fa;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.tree-arrow {
  margin-left: 5px;
}

/* 按钮样式调整 */
.el-button {
  padding: 8px 15px;
  border-radius: 4px;
}

.el-button i {
  margin-right: 5px;
}

/* 表格样式调整 */
:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: normal;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover > td) {
  background-color: #f8f9fc;
}

:deep(.el-button--text) {
  color: #409eff;
}

:deep(.el-button--text:hover) {
  color: #66b1ff;
}

:deep(.el-button--danger) {
  color: #ff4d4f;
}

:deep(.el-button--danger:hover) {
  color: #f5222d;
}

:deep(.el-icon) {
  vertical-align: middle;
}

:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-dialog) {
  --el-dialog-border-radius: 12px;
}

:deep(.el-card__body) {
  padding: 15px;
}
</style>